import { UserService } from './../service/user.service';
import { Router } from '@angular/router';
import { RequestService } from './../service/service.service';
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  validateForm: FormGroup;
  registerForm: FormGroup;
  @Output() changeLoginStatus = new EventEmitter<string>();
  // 登录逻辑处理
  submitLoginForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.valid) {
      this.loginApi.post('/v1/user/login', this.validateForm.value).subscribe(res => {
        if (res['code'] === 200) {
          const user_token = {
            token: res['data']['token'],
            userInfo: {
              username: res['data']['username'],
              avatar: res['data']['avatar']
            },
            expires: new Date().getTime() + 1000 * 60 * 60 * 23 // 过期时间为23小时,比数据库早一个小时
          }
          localStorage.setItem('USER_TOKEN', JSON.stringify(user_token))
          this.user.set('userInfo', user_token.userInfo)
          this.user.set('token', user_token.token)
          this.changeLoginStatus.emit(res['data']['token'])
          // this.message.create('success', '登录成功!')
          this.router.navigateByUrl('')
        } else {
          this.message.create('success', res['message'])
        }
      })
    }
  }
  // 注册逻辑处理
  submitRegisterForm(): void {

    const validArr = []
    for (const i in this.registerForm.controls) {
      this.registerForm.controls[i].markAsDirty();
      this.registerForm.controls[i].updateValueAndValidity();
      validArr.push(this.registerForm.controls[i])
    }
    const valid = validArr.every(item => item.valid)
    if (valid) {
      this.loginApi.post('/v1/user/register', this.registerForm.value).subscribe(res => {
        if (res && res['code'] === 200) {
          // this.message.create('success', '注册成功，请登录！')
          // 2s后跳转至登录
          setTimeout(() => {
            window.location.reload()
          }, 2000)
        }
      })
    }
  }

  constructor(private fb: FormBuilder,
    private loginApi: RequestService,
    private message: NzMessageService,
    private router: Router,
    private user: UserService) { }

  ngOnInit(): void {
    if (localStorage.getItem('USER_TOKEN')) {
      this.router.navigateByUrl('')
    }
    this.validateForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]]
    });
    this.registerForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]]
    })
  }

}
